package org.jsea.meta.api.service.fmt;

import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * --.
 * *
 * author   Jiang.hy
 * create   2022-04-11
 */
@Slf4j(topic = "MetaApi")
public class MetaApiTimeFormat implements MetaApiFormat {

    private static final String common = "yyyy-MM-dd HH:mm:ss";
    private static final MetaApiTimeFormat common_fmt = new MetaApiTimeFormat(common);
    private static final ZoneId zoneId = ZoneId.systemDefault();
    private final DateTimeFormatter format;

    public MetaApiTimeFormat(String pattern) {
        this.format = DateTimeFormatter.ofPattern(pattern);
    }

    public static MetaApiTimeFormat gen(String pattern) {
        if (pattern == null || pattern.isEmpty() || common.equals(pattern)) {
            return common_fmt;
        }
        return new MetaApiTimeFormat(pattern);
    }

    @Override
    public String format(Object obj) {
        return format.format((TemporalAccessor) obj);
    }

    /**
     * TimeFormat parse 方法只会处理请求的数据
     *
     * @param text 请求数据
     * @return Date or List[Date]
     */
    @Override
    public Object parse(String text) {
        try {
            //如果字符串中间（index > 0）存在~符号，则自动拆分
            if (text.indexOf('~') > 0) {
                String[] split = text.split("~");
                List<Object> list = new ArrayList<>(split.length);
                for (String s : split) {
                    list.add(doparse(s));
                }
                return list;
            }
            return doparse(text);
        } catch (Exception e) {
            log.error("time pares exception:", e);
        }
        return text;
    }

    public Object doparse(String time) {
        return new Date(LocalDateTime.parse(time, format).atZone(zoneId).toInstant().toEpochMilli());
    }
}
